package com.cbs.android.module.user.user.module;

import android.os.AsyncTask;
import android.os.Message;

import com.cbs.android.component.applicationutils.Global;
import com.cbs.android.component.applicationutils.network.CBSRequest;
import com.cbs.android.component.applicationutils.network.ErrorResponse;
import com.cbs.android.component.log.L;
import com.cbs.android.component.network.Request;
import com.cbs.android.component.network.Response;
import com.cbs.android.component.network.decoder.GsonDecoder;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.user.user.entity.User;
import com.cbs.android.module.user.user.handler.ModuleHandler;
import com.cbs.android.module.user.user.handler.UserChangeHandler;
import com.google.gson.Gson;

import java.net.HttpURLConnection;

/**
 * Created by broche on 2/2/16.
 */
public class LoginModule extends AsyncTask<Object, Object, Message> {
    private static final String TAG = LoginModule.class.getName();
    private static final String UrlTpl = "%s/user/api/v1/users?username=%s&password=%s";
    private static final String ErrorHint = "未知错误, 请与客服联系";
    private static final int MSG_CANCELED = 1;
    private static final int MSG_SUCCESS = 2;
    private static final int MSG_FAILURE = 3;
    private static final int MSG_EXCEPTION = 4;
    private UserChangeHandler userChangeHandler = null;
    private ModuleHandler<User> moduleHandler = null;
    private String username = "";
    private String password = "";

    public LoginModule(String username, String password, UserChangeHandler userChangeHandler, ModuleHandler<User> moduleHandler) {
        this.username = username;
        this.password = password;
        if (userChangeHandler == null) {
            this.userChangeHandler = UserModule.getDefaultLoginUserChangeHandler();
        } else {
            this.userChangeHandler = userChangeHandler;
        }
        this.moduleHandler = moduleHandler;
    }

    @Override
    protected Message doInBackground(Object... integers) {
        Message message = new Message();
        if (userChangeHandler != null) {
            String hint = userChangeHandler.shouldChange();
            if (hint != null) {
                message.what = MSG_CANCELED;
                message.obj = hint;
                return message;
            }
        }
        User user;
        try {
            Request request = new CBSRequest(String.format(UrlTpl, Global.getServerHost(), username, UserModule.getPassword(password)))
                    .setDecoder(new GsonDecoder(User.class));
            Response response = UserModule.getHttpClient().sendSync(request);
            if (response.getCode() == HttpURLConnection.HTTP_OK) { // login success
                user = ((User) response.getResult());
                UserModule.setUser(user);
            } else {
                message.what = MSG_FAILURE;
                message.obj = response;
                return message;
            }
        } catch (Exception e) {
            L.e(TAG, "", e);
            message.what = MSG_EXCEPTION;
            message.obj = e;
            return message;
        }
        if (userChangeHandler != null) {
            userChangeHandler.onChanged(user);
        }

        message.what = MSG_SUCCESS;
        message.obj = user;
        return message;
    }

    @Override
    protected void onPostExecute(Message message) {
        if (message.what == MSG_CANCELED) {
            if (moduleHandler != null) {
                ErrorResponse errorResponse = new ErrorResponse();
                errorResponse.setErrorNo(99998);
                errorResponse.setErrorMsg((String) message.obj);
                moduleHandler.onFailure(999, new Gson().toJson(errorResponse));
            }
        } else if (message.what == MSG_FAILURE) {
            if (moduleHandler != null) {
                Response response = (Response) message.obj;
                moduleHandler.onFailure(response.getCode(), response.getResult().toString());
            }
        } else if (message.what == MSG_EXCEPTION) {
            if (moduleHandler != null) {
                moduleHandler.onException((Exception) message.obj);
            }
        } else if (message.what == MSG_SUCCESS) {
            if (moduleHandler != null) {
                moduleHandler.onSuccess((User) message.obj);
            }
            // refresh push token
            UserModule.refreshPushToken();
        } else {
            if (moduleHandler != null) {
                ErrorResponse errorResponse = new ErrorResponse();
                errorResponse.setErrorNo(99999);
                errorResponse.setErrorMsg(ErrorHint);
                moduleHandler.onFailure(999, new Gson().toJson(errorResponse));
            }
        }
    }
}
